package com.shawn.integeration.batch;

import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;

/**
 * @author shawn
 * @description: 多任务批处理配置
 * @date 2024/1/7
 */
@Slf4j
//@Configuration
public class MultiJobBatchConfig {
    @Resource
    private JobBuilderFactory jobFactory;

    @Resource
    private StepBuilderFactory stepFactory;

    /**
     * 构建多步骤作业,并定义了这些步骤之间的转换规则
     */
    @Bean
    public Job multiJob() {
        return jobFactory.get("multiJob")
                //  指定作业启动步骤 multiStep1
                .start(multiStep1())
                //  指定当第1个步骤退出状态为 COMPLETED,执行步骤2 multiStep2
                .on(ExitStatus.COMPLETED.getExitCode()).to(multiStep2())
                // 从步骤2开始
                .from(multiStep2())
                // 指定当第2个步骤退出状态为 COMPLETED,执行步骤3 multiStep3
                .on(ExitStatus.COMPLETED.getExitCode()).to(multiStep3())
                // 从步骤3开始
                .from(multiStep3())
                // 表示步骤3是最后一个步骤
                .end()
                .build();
    }

    private Step multiStep1() {
        return stepFactory.get("multiStep1")
                .tasklet((stepContribution, chunkContext) -> {
                    log.info("multiStep1执行步骤一。。。");
                    return RepeatStatus.FINISHED;
                }).build();
    }

    private Step multiStep2() {
        return stepFactory.get("multiStep2")
                .tasklet((stepContribution, chunkContext) -> {
                    log.info("multiStep2执行步骤二。。。");
                    return RepeatStatus.FINISHED;
                }).build();
    }

    private Step multiStep3() {
        return stepFactory.get("multiStep3")
                .tasklet((stepContribution, chunkContext) -> {
                    log.info("multiStep3执行步骤三。。。");
                    return RepeatStatus.FINISHED;
                }).build();
    }
}
